#import <CommonCrypto/CommonDigest.h>
#import "NSString+CODEC.h"
#import "GTMBase64.h"

@implementation NSString (CODEC)

- (NSString*)MD5String
{
    const char* cStr = [self UTF8String];
    unsigned char result[CC_MD5_DIGEST_LENGTH];
    CC_MD5(cStr, (uint32_t)strlen(cStr), result); // This is the md5 call
    //return [NSString stringWithFormat:@"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
    return [NSString stringWithFormat:@"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",
            result[0], result[1], result[2], result[3],
            result[4], result[5], result[6], result[7],
            result[8], result[9], result[10], result[11],
            result[12], result[13], result[14], result[15]];
}

- (NSString*)SHA1String
{
    const char* cstr = [self UTF8String];
    NSData* data = [NSData dataWithBytes:cstr length:[self length]];
    
    uint8_t digest[CC_SHA1_DIGEST_LENGTH];
    
    CC_SHA1(data.bytes, (uint32_t)data.length, digest);
    
    NSMutableString* output = [NSMutableString stringWithCapacity:CC_SHA1_DIGEST_LENGTH * 2];
    
    for(int i = 0; i < CC_SHA1_DIGEST_LENGTH; i++)
    {
        [output appendFormat:@"%02x", digest[i]];
    }
    
    return output;
}

- (NSString*)URLEncodedString
{    
    NSString* result = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)self, NULL, CFSTR("!*'();:@&=+$,/?%#[]"), kCFStringEncodingUTF8));
//    [result autorelease];
    return result;
}

- (NSString*)URLDecodedString
{
    NSString* result = (NSString *)CFBridgingRelease(CFURLCreateStringByReplacingPercentEscapesUsingEncoding(kCFAllocatorDefault, (CFStringRef)self, CFSTR(""), kCFStringEncodingUTF8));
//    [result autorelease];
    return result;
}

+ (NSString * )encodeBase64:(NSString * )input
{
    NSData * data = [input dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
    // 转换到base64
    data = [GTMBase64 encodeData:data];
    NSString * base64String = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    return base64String;
}

+ (NSString * )decodeBase64:(NSString * )input
{
    NSData * data = [input dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
    // 转换到base64
    data = [GTMBase64 decodeData:data];
    NSString * base64String = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    return base64String;
}

//判断某字符串是否为空
+ (BOOL) isBlankString:(NSString *)string {
    if (string == nil || string == NULL) {
        return YES;
    }
    if ([string isKindOfClass:[NSNull class]]) {
        return YES;
    }
    if ([[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] length]==0) {
        return YES;
    }
    return NO;
}
//手机号是否合法
+(BOOL)isPhoneNumber:(NSString *)string
{
    if (string.length==11) {
        char v_one = [string characterAtIndex:0];
        char v_two = [string characterAtIndex:1];
        
        if (v_one == '1' && v_two != '0'  && v_two != '1'  && v_two != '2') {
            return YES;
        }
        else
            return NO;
    }
    else
        return NO;
}
//判断日期（时间戳）是否是今天（isToday） 明天（isTomorrow）昨天（isYesterday）在本周内（isWeekend）
+ (BOOL )checkTheDate:(NSString *)timeStamp withIsDateIn:(NSString *)isDateIn
{
//    NSDateFormatter *format = [[NSDateFormatter alloc]init];
//    [format setDateFormat:@"yyyy-MM-dd"];
//    NSDate *date = [format dateFromString:string];
    NSDate* date = [NSDate dateWithTimeIntervalSince1970:[timeStamp doubleValue]/1000];
    if ([isDateIn isEqualToString:@"isToday"]) {
        return [[NSCalendar currentCalendar] isDateInToday:date];
    }else if ([isDateIn isEqualToString:@"isTomorrow"]) {
        return [[NSCalendar currentCalendar] isDateInTomorrow:date];
    }else if ([isDateIn isEqualToString:@"isYesterday"]) {
        return [[NSCalendar currentCalendar] isDateInYesterday:date];
    }else if ([isDateIn isEqualToString:@"isWeekend"]) {
        return [[NSCalendar currentCalendar] isDateInWeekend:date];
    }else{
        return [[NSCalendar currentCalendar] isDateInToday:date];
    }
}

//获得特定格式的日期时间值(参数为时间戳值  毫秒)
+(NSString *)getTheDateStringByTimeStamp:(NSString *)timeStamp withFormat:(NSString *)format
{
    NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    [formatter setDateFormat:format];//@"yyyy-MM-dd-HHMMss"
    
    NSDate* date = [NSDate dateWithTimeIntervalSince1970:[timeStamp doubleValue]/1000];
    NSString *dateString = [formatter stringFromDate:date];
    return dateString;
}
//获得特定格式的日期时间值(参数为日期值)
+(NSString *)getTheDateStringBydate:(NSDate *)date withFormat:(NSString *)format
{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = format;
    NSString *dateStr = [formatter stringFromDate:date];
    return dateStr;
}

+(NSString *)changeDate:(NSDate *)date change:(NSInteger)change
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    //设定时间格式,这里可以设置成自己需要的格式
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    
    NSDate *changeDate = [NSDate dateWithTimeInterval:24*60*60*change sinceDate:date];
    return [dateFormatter stringFromDate:changeDate];
}
+ (CGFloat)getHeightByWidth:(CGFloat)width title:(NSString *)title font:(UIFont *)font
{
    
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, width, 0)];
    label.text = title;
    label.font = font;
    label.numberOfLines = 0;
    [label sizeToFit];
    CGFloat height = label.frame.size.height;
    return height;
}

+ (CGFloat)getWidthWithTitle:(NSString *)title font:(UIFont *)font {
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 1000, 0)];
    label.text = title;
    label.font = font;
    [label sizeToFit];
    return label.frame.size.width;
}
//得到当前时间的时区值(小时)
+(NSInteger )getTheUTCByDateTime:(NSDate *)date
{
    //设置源日期时区
    NSTimeZone* sourceTimeZone = [NSTimeZone timeZoneWithAbbreviation:@"UTC"];//或GMT
    //设置转换后的目标日期时区
    NSTimeZone* destinationTimeZone = [NSTimeZone localTimeZone];
    //得到源日期与世界标准时间的偏移量
    NSInteger sourceGMTOffset = [sourceTimeZone secondsFromGMTForDate:date];
    //目标日期与本地时区的偏移量
    NSInteger destinationGMTOffset = [destinationTimeZone secondsFromGMTForDate:date];
    //得到时间偏移量的差值
    NSInteger interval = destinationGMTOffset - sourceGMTOffset;
    //转为现在时间的时区
    interval = interval/3600;
    return interval;
}

//正则表达式   将{}和里面的内容替换成*****
+(NSString *)getStringByRegularExpression:(NSString *)string
{
    if ([string containsString:@"{"] && [string containsString:@"}"]) {
        NSRange range = [string rangeOfString:@"(\\{.*\\})" options:NSRegularExpressionSearch range:NSMakeRange(0, string.length) locale:nil];
        NSString *str_range = [string substringWithRange:range];
        string = [string stringByReplacingOccurrencesOfString:str_range withString:@"*****"];
    }
    return string;
}

//不四舍五入的将double数据转成字符串
+(NSString *)savePointPrecisionNotRoundNumber:(double)number afterPoint:(int)position
{
    NSDecimalNumberHandler* roundingBehavior = [NSDecimalNumberHandler decimalNumberHandlerWithRoundingMode:NSRoundDown scale:position raiseOnExactness:NO raiseOnOverflow:NO raiseOnUnderflow:NO raiseOnDivideByZero:YES];
    NSDecimalNumber *ouncesDecimal = [[NSDecimalNumber alloc] initWithDouble:number];
    NSDecimalNumber *roundedOunces = [ouncesDecimal decimalNumberByRoundingAccordingToBehavior:roundingBehavior];
    return [NSString stringWithFormat:@"%@",roundedOunces];
}
//正则表达式匹配特定字符
+(NSArray *)getArrayStringsByRegularExpression:(NSString *)expression withContent:(NSString *)content
{
    NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc] initWithString: content];
    [attrStr addAttribute:NSForegroundColorAttributeName value:[UIColor blackColor] range: NSMakeRange(0, content.length)];
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:expression options: NSRegularExpressionCaseInsensitive error:nil];
    return [regex matchesInString:content options:0 range:NSMakeRange(0, content.length)];
}

+(NSString *)randomStringWithLength:(NSInteger)len String:(NSString *)letters {
    if (letters == nil || [letters  isEqual: @""] || letters.length == 0) {
        letters = @"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    }
    NSMutableString *randomString = [NSMutableString stringWithCapacity: len];
    
    for (NSInteger i = 0; i < len; i++) {
        NSInteger index = arc4random() % (letters.length-1);
        [randomString appendFormat: @"%C", [letters characterAtIndex: index]];
    }
    return randomString;
}


@end
